<?php

namespace app\http\controller\admin\sys;

use mon\env\Config;
use mon\util\Dictionary;
use app\service\MigrateService;
use app\libs\exception\MigrateException;
use app\http\controller\admin\Controller;

/**
 * Mysql数据备份
 * 
 * @author Mon <985558837@qq.com>
 */
class MigrateController extends Controller
{
    /**
     * 查看备份数据及页面加载
     *
     * @return void
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $files = MigrateService::instance()->fileList();
            $data = [];
            foreach ($files as $key => $v) {
                $data[] = [
                    'filename'  => $v['filename'],
                    'part'      => $v['part'],
                    'size'      => $v['size'],
                    'compress'  => $v['compress'],
                    'time'      => $v['time'],
                ];
            }
            $data = array2DSort($data, 'time');
            return $this->success('ok', $data);
        }
        $tableAuth = $this->auth->check('/admin/sys/migrate/table', $this->userInfo['id']);
        $dictionaryAuth = $this->auth->check('/admin/sys/migrate/dictionary', $this->userInfo['id']);
        return $this->fetch('sys/migrate/index', [
            'tableAuth'         => $tableAuth,
            'dictionaryAuth'    => $dictionaryAuth
        ]);
    }

    /**
     * 表数据
     *
     * @return void
     */
    public function table()
    {
        return $this->success('ok', MigrateService::instance()->tableData());
    }

    /**
     * 查看表结构
     *
     * @return void
     */
    public function field()
    {
        $table = $this->request->get('table');
        if (!$table) {
            return $this->error('错误请求');
        }
        $database = Config::instance()->get('database.database');
        $sql = "SELECT * FROM `information_schema`.`columns` WHERE `TABLE_NAME` = ? AND `TABLE_SCHEMA` = ?";
        $data = \mon\orm\Db::connect()->query($sql, [$table, $database]);
        return $this->fetch('sys/migrate/field', ['data' => $data]);
    }

    /**
     * 数据字典
     *
     * @return void
     */
    public function dictionary()
    {
        return (new Dictionary(Config::instance()->get('database')))->getHTML();
    }

    /**
     * 下载备份文件
     *
     * @return void
     */
    public function download()
    {
        $filename = $this->request->get('filename');
        if (!$filename) {
            return $this->error('错误请求');
        }
        MigrateService::instance()->download($filename);
    }

    /**
     * 导入备份文件
     *
     * @return void
     */
    public function import()
    {
        return $this->success('导入功能暂未开放，尽请期待后续更新开放功能');
    }

    /**
     * 删除备份文件
     *
     * @return void
     */
    public function del()
    {
        $filename = $this->request->post('filename');
        if (check('int', $filename) !== true || check('min', $filename, '100') !== true) {
            return $this->error('params invalid!');
        }

        try {
            MigrateService::instance()->del($filename);
            return $this->success('删除成功');
        } catch (MigrateException $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 备份数据
     *
     * @return void
     */
    public function save()
    {
        $tables = $this->request->post('tables', []);
        if (!is_array($tables)) {
            return $this->error('params invalid!');
        }
        try {
            $error = [];
            foreach ($tables as $table) {
                $backup = MigrateService::instance()->backup($table);
                if ($backup === false) {
                    $error[] = $table;
                }
            }
            if (count($error) > 0) {
                return $this->error('备份失败：' . implode('，', $error));
            }
            return $this->success('备份成功');
        } catch (MigrateException $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 优化表
     *
     * @return void
     */
    public function optimize()
    {
        $tables = $this->request->post('tables');
        if (!is_array($tables)) {
            return $this->error('params invalid!');
        }
        try {
            $optimize = MigrateService::instance()->optimize($tables);
            return $this->success('优化成功');
        } catch (MigrateException $e) {
            return $this->error($e->getMessage());
        }
    }

    /**
     * 修复表
     *
     * @return void
     */
    public function repair()
    {
        $tables = $this->request->post('tables', []);
        if (!is_array($tables)) {
            return $this->error('params invalid!');
        }
        try {
            $repair = MigrateService::instance()->repair($tables);
            return $this->success('修复成功');
        } catch (MigrateException $e) {
            return $this->error($e->getMessage());
        }
    }
}
